<template>
    <div class="md-upload-avatar" v-loading="loading">
        <div class="md-avatar text-xs-center pa-2">
            <v-avatar :size="size" @click="changeAvatar">
                <img :src="data" alt="">
            </v-avatar>
            <input type="file" hidden ref="file" accept="image/*" @change="fileChange" :value="file">
        </div>
    </div>
</template>

<script>
    import vModeValue from "@/components/mixins/vModeValue";
    import fileApi from '@/comment/apis/file/Base';

    export default {
        name: "UploadAvatar",
        props: {
            size: {type: Number, default: 100}
        },
        mixins: [vModeValue],
        data () {
            return {
                file: undefined,
                loading: false
            }
        },
        methods: {
            changeAvatar() {
                this.$refs['file'].click()
            },
            fileChange(e) {
                let el = e.target;
                let file = el.files[0];
                this.loading = true;
                fileApi.uploadImage(file).then(res => {
                    console.info(res);
                    this.$util.handelHttpResponse(res, true, '上传成功').then(({data}) => {
                        this.data = data;
                    });
                }).finally(() => this.loading = false);
                el.value = '';
            }
        }
    }
</script>

<style scoped lang="scss">
    .md-upload-avatar {
        text-align: center;
        padding-bottom: 20px;

        .md-avatar {
            .v-avatar {
                cursor: pointer;
            }
        }
    }
</style>